package com.sky.controller.admin;


import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.result.Result;
import com.sky.service.OrderDetailService;
import com.sky.service.OrdersService;
import com.sky.service.UserService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/report")
@Api(tags = "数据统计")
@Slf4j
public class  ReportController {

    @Autowired
    private UserService userService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private WorkspaceService workspaceService;

    @GetMapping("/turnoverStatistics")
    @ApiOperation("营业额统计")
    public Result<TurnoverReportVO> turnoverReport(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end){

        log.info("营业额统计：{}，{}" ,begin,end);

//近哪几日
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dataList.add(begin);
        }

//        查询每日营业额
        ArrayList<Double> turnoverList = new ArrayList<>();
        dataList.stream().map((item) -> {
            LocalDateTime beginTime = LocalDateTime.of(item, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(item, LocalTime.MAX);
            HashMap map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);
            Double turnover = orderMapper.sumMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
           return item;

        }).collect(Collectors.toList());

        String joinList = StringUtils.join(dataList, ",");
        String amount = StringUtils.join(turnoverList, ",");

        TurnoverReportVO build = TurnoverReportVO.builder()
                .dateList(joinList)
                .turnoverList(amount)
                .build();

        return Result.success(build);

    }

    @GetMapping("/userStatistics")
    @ApiOperation("用户统计")
    public Result<UserReportVO> userStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end){

        log.info("用户统计：{}，{}" ,begin,end);
//近哪几日
        ArrayList<LocalDate> dataList = new ArrayList<>();
        ArrayList<Long> totalUserList = new ArrayList<>();
        ArrayList<Long> newUserList = new ArrayList<>();


        dataList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dataList.add(begin);
        }

        dataList.stream().map((everyday -> {
            LocalDateTime beginTime = LocalDateTime.of(everyday, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(everyday, LocalTime.MAX);
//            新增人数
            Long count = userService.lambdaQuery()
                    .lt(User::getCreateTime,endTime )
                    .gt(User::getCreateTime, beginTime)
                    .count();
            newUserList.add(count);
//            总人数
            long total = userService.lambdaQuery()
                    .lt(User::getCreateTime,endTime )
                    .count();
            totalUserList.add(total);

            return everyday;
        })).collect(Collectors.toList());



        String news = StringUtils.join(newUserList, ",");
        String allDays = StringUtils.join(dataList, ",");
        String totals = StringUtils.join(totalUserList, ",");

        UserReportVO build = UserReportVO.builder()
                .dateList(allDays)
                .totalUserList(totals)
                .newUserList(news)
                .build();

        return Result.success(build);

    }

    @GetMapping("/ordersStatistics")
    @ApiOperation("订单统计")
    @Transactional
    public Result<OrderReportVO> ordersStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end){

        log.info("订单统计：{}，{}" ,begin,end);
//        初始化
        ArrayList<Long> totalCountList = new ArrayList<>();
        ArrayList<Long> rateList = new ArrayList<>();
        ArrayList<Long> userfulList = new ArrayList<>();
        ArrayList<Long> dayTotalList = new ArrayList<>();


//近哪几日
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dataList.add(begin);
        }


        dataList.stream().map((everyday) -> {
//        查询每日
            LocalDateTime endTime = LocalDateTime.of(everyday, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(everyday, LocalTime.MIN);

//        查询完成率

        Long unComplete = ordersService.lambdaQuery()
                .ne(Orders::getStatus, Orders.COMPLETED)
                .lt(Orders::getOrderTime,endTime )
                .gt(Orders::getOrderTime, beginTime)
                .count();

        Long complete = ordersService.lambdaQuery()
                .eq(Orders::getStatus, Orders.COMPLETED)
                .lt(Orders::getOrderTime,endTime )
                .gt(Orders::getOrderTime, beginTime)
                .count();
        if (complete == null) {
            rateList.add(0L);

        }else if(unComplete == 0){
            rateList.add(1L);
        }else {
            Long orderRate = complete / unComplete;
            orderRate = orderRate == null ? 0 : orderRate;
            rateList.add(orderRate);
        }
//      订单总数

            Long total = ordersService.lambdaQuery()
                    .lt(Orders::getOrderTime, endTime)
                    .count();

            total = total == null ? 0 : total;
            totalCountList.add(total);
//      每日有效订单数，以逗号分隔，例如：20,21,10

            Long useful = ordersService.lambdaQuery()
                    .lt(Orders::getOrderTime, endTime)
                    .gt(Orders::getOrderTime, beginTime)
                    .eq(Orders::getStatus,Orders.COMPLETED)
                    .count();
            useful = useful == null ? 0 : useful;

            userfulList.add(useful);

//           每日订单数
            Long dayTotal = ordersService.lambdaQuery()
                    .lt(Orders::getOrderTime, endTime)
                    .gt(Orders::getOrderTime, beginTime)
                    .count();
            dayTotal = dayTotal == null ? 0 : dayTotal;
            dayTotalList.add(dayTotal);

            return everyday;

        }).collect(Collectors.toList());


        Double rates = Double.valueOf(Collections.max(rateList));
        String joinList = StringUtils.join(dataList, ",");
        String userfulLists = StringUtils.join(userfulList, ",");
        String dayTatolS = StringUtils.join(dayTotalList, ",");

        OrderReportVO build = OrderReportVO.builder()
                .dateList(joinList)
                .orderCompletionRate(rates)
                .validOrderCountList(userfulLists)
                .totalOrderCount(0)
                .validOrderCount(0)
                .orderCountList(dayTatolS)
                .build();

        return Result.success(build);

    }

    @GetMapping("/top10")
    @ApiOperation("订单统计")
    @Transactional
    public Result<SalesTop10ReportVO> top10(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {


        ArrayList<LocalDate> dataList = new ArrayList<>();
        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<BigDecimal> priceList = new ArrayList<>();

        //近哪几日
        dataList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dataList.add(begin);
        }

        dataList.stream().map((everyday) ->{
            LocalDateTime beginTime = LocalDateTime.of(everyday,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(everyday,LocalTime.MAX);


            List<Orders> numberList = ordersService.lambdaQuery()
                    .lt(Orders::getOrderTime, endTime)
                    .gt(Orders::getOrderTime, beginTime)
                    .eq(Orders::getStatus,Orders.COMPLETED)
                    .list();
            numberList.stream().map((item) -> {

                List<OrderDetail> names = orderDetailService.lambdaQuery()
                        .eq(OrderDetail::getOrderId, item.getId())
//                        .groupBy(OrderDetail::getName)
                        .orderByDesc(OrderDetail::getNumber)
                        .list();

                names.stream().map((name) -> {
                    String name1 = name.getName();
                    BigDecimal price = name.getAmount();
                    if(nameList.size() < 10){
                        nameList.add(name1);
                        priceList.add(price);

                    }
                    return name;

                }).collect(Collectors.toList());
                return item;
            }).collect(Collectors.toList());
            return everyday;
        }).collect(Collectors.toList());


        String nameRes = StringUtils.join(nameList);
        String amount = StringUtils.join(priceList,",");

        SalesTop10ReportVO build = SalesTop10ReportVO.builder()
                .nameList(nameRes)
                .numberList(amount)
                .build();

        return Result.success(build);

        }

        @GetMapping("/export")
        @ApiOperation("导出运营数据报表")
        public void export(HttpServletResponse response){
            LocalDate begin = LocalDate.now().minusDays(30);
            LocalDate end = LocalDate.now().minusDays(1);
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

//      查询概览数据
            BusinessDataVO dataVO = workspaceService.getBusinessData(beginTime, endTime);

            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

            try {
//                基于模板文件创建新的Excel文件
                XSSFWorkbook excel = new XSSFWorkbook(inputStream);
//                获取sheet页
                XSSFSheet sheet = excel.getSheet("sheet1");
                sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + " ~ " + end);

                sheet.getRow(3).getCell(2).setCellValue(dataVO.getTurnover());
                sheet.getRow(3).getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                sheet.getRow(3).getCell(6).setCellValue(dataVO.getNewUsers());
                sheet.getRow(4).getCell(2).setCellValue(dataVO.getValidOrderCount());
                sheet.getRow(4).getCell(4).setCellValue(dataVO.getUnitPrice());

                for (int i = 0; i < 30; i++) {
                    LocalDate data = begin.plusDays(i);
                    BusinessDataVO vo = workspaceService.getBusinessData(LocalDateTime.of(data, LocalTime.MIN)
                            , LocalDateTime.of(data, LocalTime.MAX));
                    XSSFRow row = sheet.getRow(7 + i);
                    row.getCell(1).setCellValue(data.toString());
                    row.getCell(2).setCellValue(vo.getTurnover());
                    row.getCell(3).setCellValue(vo.getValidOrderCount());
                    row.getCell(4).setCellValue(vo.getOrderCompletionRate());
                    row.getCell(5).setCellValue(vo.getUnitPrice());
                    row.getCell(6).setCellValue(vo.getNewUsers());

                }
//               获取输出流对象，从浏览器下载
                ServletOutputStream outputStream = response.getOutputStream();
                excel.write(outputStream);

                excel.close();
                outputStream.close();

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }


